package com.xs.nlp.generaltrans;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;



import com.xs.tencent.sign.MD5;
import com.xs.util.baidu.HttpGet;

public class TransUtil {
	private static final String TRANS_API_HOST = "https://fanyi-api.baidu.com/api/trans/vip/translate";

	private String appid;
	private String securityKey;

	public TransUtil(String appid, String securityKey) {
		this.appid = appid;
		this.securityKey = securityKey;
	}

	public String getTransResult(String query, String from, String to) throws Exception {
		Map<String, String> params = buildParams(query, from, to);
		return HttpGet.get(TRANS_API_HOST, params);
	}

	private Map<String, String> buildParams(String query, String from, String to) throws UnsupportedEncodingException {
		Map<String, String> params = new HashMap<String, String>();
		params.put("q", query);
		params.put("from", from);
		params.put("to", to);

		params.put("appid", appid);
		// 随机数
		String salt = String.valueOf(System.currentTimeMillis());
		params.put("salt", salt);
		// 签名
		String src = appid + query + salt + securityKey; // 加密前的原文
		System.out.println(src);
		params.put("sign", MD5.getMD5(src).toLowerCase());
		return params;
	}
}
